import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../base/Constant.dart';
import '../../entity/order_list_entity.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../util/SignUtil.dart';

class AllTeamOrderPage extends StatefulWidget {
  var type;
  AllTeamOrderPage({Key key, @required this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return AllOrderView();
  }
}

// 订单状态
// 1待付款
// 2已付款、待发货
// 3已发货、待确认收货
// 4已确认收货、待评价
// 5已完成
// 6退换货

class AllOrderView extends State<AllTeamOrderPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  List<OrderListDataData> dataList = List();
  int page = 1;
  EasyRefreshController _controller = new EasyRefreshController();
  String token = "";
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Container(
      child: new Container(
        color: divideColor,
        child: new EasyRefresh(
          controller: _controller,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          child: ListView.separated(
              itemBuilder: _renderRow,
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  color: divideColor,
                  height: 5,
                );
              },
              itemCount: dataList == null ? 0 : dataList.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderDetailPage(
        //     id: dataList[index].id,
        //   );
        // }));
      },
      child: new Container(
        margin: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_15)),
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(10)),
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                  child: Text("团队成员: " + dataList[index].consignee,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE+3),
                          color: Colors.black)),
                ),
                Text(
                    dataList[index].status == "1"
                        ? '待付款'
                        : dataList[index].status == "2"
                            ? "待发货"
                            : dataList[index].status == "3" ? "待收货" : "待评价",
                    style: TextStyle(
                        color: mainColor,
                        fontSize:
                            ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)))
              ],
            ),
            Container(
              height: 10,
            ),
            Container(
              child: ListView.builder(
                padding: EdgeInsets.all(0),
                physics: new NeverScrollableScrollPhysics(),
                itemBuilder: (BuildContext context, int index1) {
                  return GestureDetector(
                      onTap: () {
                        // Navigator.of(context)
                        //     .push(MaterialPageRoute(builder: (context) {
                        //   return OrderDetailPage(
                        //     id: dataList[index].id,
                        //   );
                        // }));
                      },
                      child: Container(
                          margin: EdgeInsets.all(10),
                          child: Column(
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  ClipRRect(
                                      borderRadius: BorderRadius.circular(2),
                                      child: CachedNetworkImage(
                                        width: ScreenUtil.getInstance()
                                            .setHeight(DP_120),
                                        fit: BoxFit.fill,
                                        height: ScreenUtil.getInstance()
                                            .setHeight(DP_120),
                                        imageUrl: Api.ImgBaseUrl +
                                            dataList[index].datas[index1].img,
                                        placeholder: (context, url) =>
                                            Image.asset(
                                                'images/pic_default.png',
                                                width: ScreenUtil.getInstance()
                                                    .setHeight(DP_120),
                                                fit: BoxFit.fill,
                                                height: ScreenUtil.getInstance()
                                                    .setHeight(DP_120)),
                                        errorWidget: (context, url, error) =>
                                            Image.asset(
                                                'images/pic_default.png',
                                                width: ScreenUtil.getInstance()
                                                    .setHeight(DP_120),
                                                fit: BoxFit.fill,
                                                height: ScreenUtil.getInstance()
                                                    .setHeight(DP_120)),
                                      )),
                                  Container(
                                    width: 10,
                                  ),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                            dataList[index]
                                                .datas[index1]
                                                .goods_name,
                                            maxLines: 2,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(
                                                            SMALL_FONT_SIZE))),
                                        Container(
                                          height: 4,
                                        ),
                                        Container(
                                          width: (MediaQuery.of(context)
                                                  .size
                                                  .width -
                                              ScreenUtil.getInstance()
                                                  .setHeight(DP_250)),
                                          child: Html(
                                              data: dataList[index]
                                                  .datas[index1]
                                                  .sku_str,
                                              defaultTextStyle: TextStyle(
                                                  color: Colors.black45,
                                                  fontSize: ScreenUtil
                                                          .getInstance()
                                                      .setSp(SMALL_FONT_SIZE))),
                                        ),
                                        Container(
                                          height: 6,
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Text(
                                                MONEY +
                                                    dataList[index]
                                                        .datas[index1]
                                                        .price +
                                                    '; ',
                                                style: TextStyle(
                                                    color: black,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE))),
                                            // Container(
                                            //   width:
                                            //       (MediaQuery.of(context).size.width -
                                            //           ScreenUtil.getInstance()
                                            //               .setHeight(DP_350)),
                                            // ),
                                            Text(
                                                "x" +
                                                    dataList[index]
                                                        .datas[index1]
                                                        .num,
                                                style: TextStyle(
                                                    color: black,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            SMALL_FONT_SIZE))),
                                          ],
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                              Container(
                                height: 10,
                              ),
                              Container(
                                  width: double.infinity,
                                  alignment: Alignment.centerRight,
                                  child: RichText(
                                      text: TextSpan(children: [
                                    TextSpan(
                                        text: "共" +
                                            dataList[index].datas[index1].num +
                                            '件商品 ',
                                        style: TextStyle(
                                            color: Colors.grey,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(SMALL_FONT_SIZE))),
                                    TextSpan(
                                        text:
                                            "订单金额 ¥" + dataList[index].allprice,
                                        style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE))),
                                  ]))),
                            ],
                          )));
                },
                itemCount: dataList[index].datas.length,
                shrinkWrap: true,
              ),
            ),

            Container(
              height: 10,
            ),
            // Text(
            //     "收货人: " +
            //         dataList[index].consignee.toString() +
            //         "   " +
            //         dataList[index].contact_number.toString(),
            //     style: TextStyle(
            //         color: black_99,
            //         fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),

            // Container(
            //   height: 10,
            // ),
           ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    getString(TOKEN).then((value) {
      token = value;
      if (token == null) {
        return;
      }
      loadList();
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed)
      getString(TOKEN).then((value) {
        token = value;
      });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    if (widget.type.toString() == '0') {
      map['status'] = '';
    } else {
      map['status'] = widget.type.toString();
    }

    map['p'] = page.toString();
    map['per'] = '10';
    map['sign_type'] = createSignType(Api.URL_ORDER_LIST);
    Response<String> response =
        await HttpUtil().post(Api.BaseUrl+"/index.php/wap/User/getTeamOrderList", data: getSign(map));
    Map userMap = json.decode(response.data);
        print(response);

    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    OrderListEntity homeListEntity = new OrderListEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data);
        } else {
          dataList.addAll(homeListEntity.data);
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(noMore: homeListEntity.data.length == 0);
          if (homeListEntity.data.length == 0) {
            Fluttertoast.showToast(msg: "暂无更多数据");
          }
        }
      });
  }

  del(id) async {
    // FormData formData = new FormData.fromMap({
    //   "token": token,
    //   "id": id,
    // });
    // Response<String> response =
    //     await HttpUtil().post(Api.DEL_ORDER, data: formData);
    // Map userMap = json.decode(response.data);
    // int code = userMap["code"];
    // String msg = userMap["msg"];
    // Navigator.of(context).pop(1);
    // Fluttertoast.showToast(msg: msg);
    // if (code == 0) {
    //   page = 1;
    //   loadList();
    // }
    // return true;
  }

  confirm(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = dataList[index].id;
    map['sign_type'] = createSignType(Api.URL_ORDER_CONFIRM);
    Response<String> response =
        await HttpUtil().post(Api.URL_ORDER_CONFIRM, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
    return true;
  }

  cancle(int index) async {
    Map map = new Map();
    map['token'] = token;
    map['order_id'] = dataList[index].id.toString();
    map['sign_type'] = createSignType(Api.URL_ORDER_CANCEL);
    Response<String> response =
        await HttpUtil().post(Api.URL_ORDER_CANCEL, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      dataList.removeAt(index);
      setState(() {});
    }
    return true;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
